import 'dart:isolate';

/// isolate入口方法，处理多语言Map的合并与解析
/// [message] 结构：{
///   'local': Map<String, String> 本地Map，
///   'remote': Map<String, dynamic> 远程Map（可为null），
/// }
/// 返回：合并后的Map<String, String>
void languageMapIsolateEntry(dynamic message) async {
  final SendPort sendPort = message['sendPort'];
  final Map<String, String> local = Map<String, String>.from(message['local'] ?? {});
  final Map<String, dynamic> remote = Map<String, dynamic>.from(message['remote'] ?? {});

  // 合并逻辑：远程优先覆盖本地
  final Map<String, String> merged = {...local};
  remote.forEach((key, value) {
    merged[key] = value.toString().replaceAll(r'\n', '\n');
  });

  sendPort.send(merged);
}

/// 启动isolate进行多语言Map合并
/// [local] 本地Map
/// [remote] 远程Map
/// 返回合并后的Map<String, String>
Future<Map<String, String>> mergeLanguageMapInIsolate({
  required Map<String, String> local,
  Map<String, dynamic>? remote,
}) async {
  final receivePort = ReceivePort();
  await Isolate.spawn(languageMapIsolateEntry, {
    'sendPort': receivePort.sendPort,
    'local': local,
    'remote': remote ?? {},
  });
  final merged = await receivePort.first as Map<String, String>;
  receivePort.close();
  return merged;
}
